﻿#include "chatwidget.h"
#include "ui_chatwidget.h"

ChatWidget::ChatWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ChatWidget)
{
    ui->setupUi(this);
    setShadow();
    setMouseTrack();
    loadImg();
    m_pChatSocket = ChatSocket::getInstance();
    connect(this,&ChatWidget::textMsg,m_pChatSocket,&ChatSocket::sendTextMsg);
    ui->textEdit->setEnabled(true);
    ui->textEdit->setFocus();
}

ChatWidget::~ChatWidget()
{
    delete ui;
}

void ChatWidget::setWinName(QString nickname)
{
    ui->btn_nickname->setText(nickname);
}

QString ChatWidget::getWinName()
{
    return ui->btn_nickname->text();
}

void ChatWidget::setShadow()
{
    //设置无边框
    setWindowFlags(Qt::FramelessWindowHint);
    //设置窗体透明
    setAttribute(Qt::WA_TranslucentBackground, true);
    QGraphicsDropShadowEffect *shadow=new QGraphicsDropShadowEffect();
    shadow->setBlurRadius(15);//设置圆角半径
    shadow->setColor(QColor(0,0,0));//设置边框颜色
    shadow->setOffset(0,0);
    ui->mainwidget->setStyleSheet("background-color:white");
    ui->mainwidget->setGraphicsEffect(shadow);
}

void ChatWidget::loadImg()
{
    QIcon iconClose = QIcon("res/Icon/close.png");
    QIcon iconMin = QIcon("res/Icon/min.png");
    QIcon iconFile = QIcon("res/Icon/files.png");
    QIcon iconImg = QIcon("res/Icon/photo.png");
    QIcon iconShake = QIcon("res/Icon/mianxingtubiao_zhendong.png");
    QIcon iconScreenShot = QIcon("res/Icon/caijian.png");
    QIcon iconFace = QIcon("res/Icon/weixiao.png");
    QIcon iconAudio = QIcon("res/Icon/audio.png");
    QIcon iconVideo = QIcon("res/Icon/media.png");
    ui->tool_img->setIcon(iconImg);
    ui->tool_min->setIcon(iconMin);
    ui->tool_close->setIcon(iconClose);
    ui->tool_face->setIcon(iconFace);
    ui->tool_file->setIcon(iconFile);
    ui->tool_audio->setIcon(iconAudio);
    ui->tool_video->setIcon(iconVideo);
    ui->tool_shake->setIcon(iconShake);
    ui->tool_screenshot->setIcon(iconScreenShot);
}

ChatWidget::BorderIndex ChatWidget::getRegion(QPoint pos)
{
    BorderIndex region_index = BORDER_NONE;
    int offset = 18;
    auto x = pos.x();
    auto y = pos.y();
    auto w = this->width();
    auto h = this->height();
    if (y <= offset && y >= offset/4 && x > offset && x < w - offset) {
        region_index = BORDER_TOP;
    }
    else if (x <= offset && x >= offset/4 && y > offset && y < h - offset) {
        region_index = BORDER_LEFT;
    }
    else if (x >= w - offset && x <= w - offset/4 && y > offset && y < h - offset) {
        region_index = BORDER_RIGHT;
    }
    else if (y >= h - offset && y <= h - offset/4 && x > offset && x < w - offset) {
        region_index = BORDER_BOTTOM;
    }
    else if (x >= offset / 4 && x < offset && y >= offset / 4 && y < offset) {
        region_index = BORDER_LEFT_TOP;
    }
    else if (x > w - offset && x <= w - offset/4 && y >= offset / 4 && y < offset) {
        region_index = BORDER_RIGHT_TOP;
    }
    else if (x >= offset / 4 && x < offset && y > h - offset && y <= h - offset/4) {
        region_index = BORDER_LEFT_BOTTOM;
    }
    else if (x > w - offset && x <= w - offset/4 && y > h - offset && y <= h - offset/4) {
        region_index = BORDER_RIGHT_BOTTOM;
    }

    return region_index;
}

void ChatWidget::setMouseTrack()
{
    QObjectList child_object_list = ui->mainwidget->children();
    for (auto child_object : child_object_list)
    {
        if (child_object->isWidgetType()) { ((QWidget*)child_object)->setMouseTracking(true); }
    }
    ui->mainwidget->setMouseTracking(true);
    setMouseTracking(true);
}

void ChatWidget::SetCursorByRegoinIndex(ChatWidget::BorderIndex region_index)
{
    switch (region_index)
    {
        case BORDER_TOP:
        case BORDER_BOTTOM:
          this->setCursor(Qt::SizeVerCursor);
          break;
        case BORDER_LEFT:
        case BORDER_RIGHT:
          this->setCursor(Qt::SizeHorCursor);
          break;
        case BORDER_LEFT_TOP:
        case BORDER_RIGHT_BOTTOM:
          this->setCursor(Qt::SizeFDiagCursor);
          break;
        case BORDER_RIGHT_TOP:
        case BORDER_LEFT_BOTTOM:
          this->setCursor(Qt::SizeBDiagCursor);
          break;
        default:
          this->setCursor(Qt::ArrowCursor);
          break;
    }
}

QWidget *ChatWidget::CreateWidgetL_R(int i, QString name, QString data)
{
    QFont font1;
    font1.setFamily("Microsoft YaHei");
    font1.setPointSize(15);
    QWidget * widget = new QWidget();
    widget->setMaximumWidth(750);
    widget->setStyleSheet("background:rgba(0,0,0,0);");
    QHBoxLayout *horLayout = new QHBoxLayout();//水平布局
    horLayout->setContentsMargins(0,0,0,0);
    horLayout->setSpacing(0);
    QPushButton * btnicon = new QPushButton();
    btnicon->setFixedSize(50,50);
    btnicon->setIconSize(QSize(50,50));
    btnicon->setStyleSheet("background:rgba(0,0,0,0);");
    QLabel * label = new QLabel(widget);
    label->setMaximumWidth(700);
    label->setContentsMargins(5,5,5,5);
    label->setWordWrap(true);
    label->setFont(font1);
    label->setAlignment(Qt::AlignLeft);
    if(i%2)//对方消息
    {
        label->setStyleSheet("background-color: rgb(140, 105, 255);border-style:solid;border-width:2px;border-color: rgb(125, 242, 255);border-radius:10px;");
        horLayout->addWidget(btnicon,0,Qt::AlignTop);
        horLayout->addWidget(label,0,Qt::AlignLeft);
    }
    else//我方消息
    {
        label->setStyleSheet("background-color: rgb(232, 100, 150);border-style:solid;border-width:2px;border-color: rgb(100, 150, 255);border-radius:10px;");
        horLayout->addWidget(label,0,Qt::AlignLeft);
        horLayout->addWidget(btnicon,0,Qt::AlignTop);
    }
    label->setText(data);
    label->adjustSize();
    label->setFixedSize(label->size());
    label->setTextInteractionFlags(Qt::TextSelectableByMouse);
    qDebug()<<label->size()<<endl;
    //拼和消息头像
    QString headpath = ChatDB::getInstance()->getImgUrl(name);
//    QString path = QCoreApplication::applicationDirPath();
//    headpath = QString("%1/%2").arg(path).arg(headpath);
    btnicon->setIcon(QPixmap(headpath));
    //设置布局
    widget->setLayout(horLayout);
    widget->adjustSize();
    widget->setFixedSize(widget->size());
    qDebug()<<widget->size()<<endl;
    return widget;
}

void ChatWidget::addMsgWidget(QWidget *widget)
{
    ui->verticalLayout_3->addWidget(widget,0,Qt::AlignLeft);
}

void ChatWidget::restoreChatLog(QString msg)
{
    QStringList list = msg.split("&");
    list[2] = list[2].replace("わ","");
    QWidget * widget = new QWidget();
    widget->setMaximumWidth(700);
    widget->setStyleSheet("background:rgba(0,0,0,0);");
    QHBoxLayout *horLayout = new QHBoxLayout();//水平布局
    horLayout->setContentsMargins(0,0,0,0);
    horLayout->setSpacing(0);
    list[1] = list[1].mid(0,list[1].length()-2);
    list[2] = list[2].mid(0,list[2].length()-2);
    QLabel * label = new QLabel(list[1]);
    label->setMaximumWidth(700);
    label->setAlignment(Qt::AlignHCenter | Qt::AlignBottom);
    label->adjustSize();
    horLayout->addWidget(label);
    widget->setLayout(horLayout);
    widget->adjustSize();
    ui->verticalLayout_3->addWidget(widget,0,Qt::AlignHCenter);
    if(list[0]==Widget::getInstance()->getID())
        ui->verticalLayout_3->addWidget(CreateWidgetL_R(0,list[0],list[2]),0,Qt::AlignRight);
    else
        ui->verticalLayout_3->addWidget(CreateWidgetL_R(1,list[0],list[2]),0,Qt::AlignLeft);
}


void ChatWidget::mousePressEvent(QMouseEvent *event)
{
    if(event->buttons() == Qt::LeftButton)
    {
        isPressedWidget = true; // 当前鼠标按下的是QWidget而非界面上布局的其它控件
        last_position = event->globalPos();
        last_point = pos();
        m_mouse_region = getRegion(event->pos());
    }
}

void ChatWidget::mouseMoveEvent(QMouseEvent *event)
{
    if(this->isMaximized())
        return;
    BorderIndex index = getRegion(event->pos());
    SetCursorByRegoinIndex(index);
    if(isPressedWidget && event->buttons() == Qt::LeftButton)
    {
        QRect rect = geometry();
        QPoint offset = event->globalPos() - last_position;
        if(m_mouse_region == BORDER_NONE)
        {
            move(last_point+offset);
        }
        else
        {
            switch (m_mouse_region)
            {
                case BORDER_TOP:
                {
                    rect.setTop(rect.top()+offset.y());
                    break;
                }
                case BORDER_LEFT:
                {
                    rect.setLeft(rect.left()+offset.x());
                    break;
                }
                case BORDER_RIGHT:
                {
                    rect.setRight(rect.right()+offset.x());
                    break;
                }
                case BORDER_BOTTOM:
                {
                    rect.setBottom(rect.bottom()+offset.y());
                    break;
                }
                case BORDER_LEFT_TOP:
                {
                    rect.setTopLeft(rect.topLeft()+offset);
                    break;
                }
                case BORDER_LEFT_BOTTOM:
                {
                    rect.setBottomLeft(rect.bottomLeft()+offset);
                    break;
                }
                case BORDER_RIGHT_TOP:
                {
                    rect.setTopRight(rect.topRight()+offset);
                    break;
                }
                case BORDER_RIGHT_BOTTOM:
                {
                    rect.setBottomRight(rect.bottomRight()+offset);
                    break;
                }
                default:
                break;
            }
            setGeometry(rect);
            last_position = event->globalPos();
        }
    }
}

void ChatWidget::mouseReleaseEvent(QMouseEvent *event)
{
    isPressedWidget = false; // 鼠标松开时，置为false
}

void ChatWidget::on_tool_close_clicked()
{
    hide();
}

void ChatWidget::on_btn_sendMsg_clicked()
{
    if(ui->textEdit->toPlainText().size()>=1024)
    {
        QMessageBox::warning(this,"警告","消息长度不能超过1023");
        return;
    }
    if(ui->textEdit->toPlainText().isEmpty())return;
    QString msg = ui->textEdit->toPlainText();    
    ui->textEdit->clear();
    QString name = Widget::getInstance()->getID();
    ui->verticalLayout_3->addWidget(CreateWidgetL_R(0,name,msg),0,Qt::AlignRight);
    emit textMsg(msg,ui->btn_nickname->text());
}
